<template>
  <div class="resume-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入姓名"
            clearable
            @clear="handleSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="学校">
          <el-input
            v-model="searchForm.school"
            placeholder="请输入学校"
            clearable
            @clear="handleSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="学历">
          <el-select v-model="searchForm.education" placeholder="请选择学历" clearable @clear="handleSearch">
            <el-option label="大专" value="college"></el-option>
            <el-option label="本科" value="bachelor"></el-option>
            <el-option label="硕士" value="master"></el-option>
            <el-option label="博士" value="phd"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="name"
        label="姓名"
        min-width="100"
      ></el-table-column>
      <el-table-column
        prop="education"
        label="学历"
        min-width="100"
      >
        <template slot-scope="scope">
          {{ educationMap[scope.row.education] || scope.row.education }}
        </template>
      </el-table-column>
      <el-table-column
        prop="school"
        label="学校"
        min-width="150"
      ></el-table-column>
      <el-table-column
        prop="phone"
        label="电话"
        min-width="120"
      ></el-table-column>
      <el-table-column
        prop="station"
        label="投递岗位"
        min-width="120"
      >
        <template slot-scope="scope">
          {{ scope.row.station || '-' }}
        </template>
      </el-table-column>
      <el-table-column
        label="简历"
        min-width="100"
        align="center"
      >
        <template slot-scope="scope">
          <el-button 
            type="text" 
            @click="downloadResume(scope.row)"
            v-if="scope.row.resumeAttachment"
          >
            下载简历
          </el-button>
          <span v-else>暂无简历</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        min-width="100"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.state === 1">已通过</el-tag>
          <el-tag type="danger" v-else-if="scope.row.state === 2">已驳回</el-tag>
          <el-tag v-else>待处理</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
            v-if="!isProcessed(scope.row)"
            size="mini"
            type="text"
            @click="handleApprove(scope.row)"
          >同意</el-button>
          <el-button
            v-if="!isProcessed(scope.row)"
            size="mini"
            type="text"
            class="reject-btn"
            @click="handleReject(scope.row)"
          >驳回</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <pagination
      :current-page.sync="pagination.current"
      :page-size.sync="pagination.size"
      :total="pagination.total"
      @pagination-change="fetchResumeData"
    />
    
    <!-- 简历详情对话框 -->
    <el-dialog
      title="简历详情"
      :visible.sync="detailDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      :modal="true"
      :append-to-body="true"
      :modal-append-to-body="false"
      :destroy-on-close="true"
    >
      <div class="resume-detail">
        <div class="resume-header">
          <div class="resume-name">{{ currentResume.name }}</div>
          <div class="resume-gender">{{ currentResume.gender === 0 ? '男' : '女' }}</div>
        </div>
        
        <el-divider></el-divider>
        
        <div class="detail-section">
          <div class="detail-item">
            <span class="item-label">联系电话：</span>
            <span class="item-value">{{ currentResume.phone }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">电子邮箱：</span>
            <span class="item-value">{{ currentResume.email }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">毕业院校：</span>
            <span class="item-value">{{ currentResume.school }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">学历：</span>
            <span class="item-value">{{ educationMap[currentResume.education] || currentResume.education }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">应聘职位：</span>
            <span class="item-value">{{ jobPosition.title || '获取中...' }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">所属部门：</span>
            <span class="item-value">{{ jobPosition.department || '获取中...' }}</span>
          </div>
          <div class="detail-item">
            <span class="item-label">性格测试结果：</span>
            <span class="item-value">{{ getPersonalityResult(currentResume.personalityTestResult) }}</span>
          </div>
          
          <!-- 添加岗位职责 -->
          <div class="detail-item detail-textarea" v-if="jobPosition.responsibility">
            <span class="item-label">岗位职责：</span>
            <div class="item-value pre-formatted">{{ jobPosition.responsibility }}</div>
          </div>
          
          <!-- 添加任职要求 -->
          <div class="detail-item detail-textarea" v-if="jobPosition.requirement">
            <span class="item-label">任职要求：</span>
            <div class="item-value pre-formatted">{{ jobPosition.requirement }}</div>
          </div>
          
          <div class="detail-item">
            <span class="item-label">备注：</span>
            <span class="item-value">{{ currentResume.notes || '无' }}</span>
          </div>
        </div>
        
        <div class="detail-section" v-if="currentResume.resumeAttachment">
          <div class="detail-item">
            <span class="item-label">简历附件：</span>
            <el-button type="text" @click="downloadResume(currentResume)">
              <i class="el-icon-download"></i> 下载简历
            </el-button>
          </div>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          v-if="!isProcessed(currentResume)"
          type="primary" 
          @click="handleApproveFromDialog"
        >同意</el-button>
        <el-button 
          v-if="!isProcessed(currentResume)"
          type="danger" 
          @click="handleRejectFromDialog"
        >驳回</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/common/Pagination.vue'

export default {
  name: 'RecruitmentResumes',
  components: {
    Pagination
  },
  data() {
    return {
      loading: false,
      searchForm: {
        name: '',
        school: '',
        education: '',
        state: ''
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      educationMap: {
        'college': '大专',
        'bachelor': '本科',
        'master': '硕士',
        'phd': '博士'
      },
      // 简历详情对话框
      detailDialogVisible: false,
      currentResume: {},
      jobPosition: {
        title: '',
        department: '',
        responsibility: '',
        requirement: ''
      }
    }
  },
  created() {
    this.fetchResumeData()
  },
  methods: {
    // 获取简历数据
    async fetchResumeData() {
      try {
        this.loading = true
        const params = {
          name: this.searchForm.name || undefined,
          school: this.searchForm.school || undefined,
          education: this.searchForm.education || undefined,
          state: this.searchForm.state || undefined,
          current: this.pagination.current,
          size: this.pagination.size
        }
        
        const response = await this.$axios.get('/recruitment/resume', {
          params: params
        })
        
        if (response && response.result === 200) {
          const { records, total, size, current } = response.data
          this.tableData = records
          this.pagination = {
            total,
            size,
            current
          }
        } else {
          this.showMessage('error', response.message || '获取简历数据失败')
        }
      } catch (error) {
        console.error('获取简历数据出错：', error)
        this.$message.error('获取简历数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.fetchResumeData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        name: '',
        school: '',
        education: ''
      }
      this.handleSearch()
    },

    // 下载简历
    downloadResume(row) {
      if (row.resumeAttachment) {
        window.open(row.resumeAttachment)
      } else {
        this.$message.warning('简历文件不存在')
      }
    },

    // 查看简历
    async handleView(row) {
      this.currentResume = {...row}
      this.detailDialogVisible = true
      // 获取职位信息
      this.fetchJobPositionInfo(row.jobPostingsId)
    },

    // 获取职位信息
    async fetchJobPositionInfo(jobId) {
      if (!jobId) return
      
      try {

        const response = await this.$axios.get(`/recruitment/jobPostings/one?id=${jobId}`)
        
        if (response && response.result === 200 && response.data) {
          this.jobPosition = {
            title: response.data.title || '未知职位',
            department: response.data.department || '未知部门',
            responsibility: response.data.responsibility || '',
            requirement: response.data.requirement || ''
          }
        } else {
          this.jobPosition = { 
            title: '获取失败', 
            department: '获取失败',
            responsibility: '',
            requirement: ''
          }
        }
      } catch (error) {
        console.error('获取职位信息出错：', error)
        this.jobPosition = { 
          title: '获取失败', 
          department: '获取失败',
          responsibility: '',
          requirement: ''
        }
      }
    },

    // 获取性格测试结果文本
    getPersonalityResult(result) {
      const resultMap = {
        0: 'A型性格',
        1: 'B型性格',
        2: 'C型性格',
        3: 'D型性格'
      }
      return resultMap[result] || '未知'
    },

    // 从对话框中同意
    handleApproveFromDialog() {
      this.handleApprove(this.currentResume)
      this.detailDialogVisible = false
    },

    // 从对话框中驳回
    handleRejectFromDialog() {
      this.handleReject(this.currentResume)
      this.detailDialogVisible = false
    },

    // 同意
    async handleApprove(row) {
      try {
        this.$confirm('确认同意该应聘者的简历吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(async () => {
          
          try {
            const response = await this.$axios.post('/recruitment/resume/rejectOrApprove', null, {
              params: {
                resumeId: row.id,
                comment: '同意'
              }
            })
            
            if (response && response.result === 200) {
              this.$message.success('已同意该简历')
              this.fetchResumeData() // 刷新数据
            } else {
              this.$message.error(response.message || '操作失败')
            }
          } catch (error) {
            console.error('同意简历出错：', error)
            this.$message.error('操作失败')
          } 
        }).catch(() => {
          // 取消操作
        })
      } catch (error) {
        console.error('同意操作出错：', error)
      }
    },

    // 驳回
    async handleReject(row) {
      this.$confirm('确认驳回该应聘者的简历吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(async () => {
          try {
            const response = await this.$axios.post('/recruitment/resume/rejectOrApprove', null, {
              params: {
                resumeId: row.id,
                comment: '驳回'
              }
            })
            
            if (response && response.result === 200) {
              this.$message.success('已驳回该简历')
              this.fetchResumeData() // 刷新数据
            } else {
              this.$message.error(response.message || '操作失败')
            }
          } catch (error) {
            console.error('驳回简历出错：', error)
            this.$message.error('操作失败')
          } 
        })
    },

    // 判断简历是否已处理（已通过或已驳回）
    isProcessed(row) {
      return row.state === 1 || row.state === 2
    }
  }
}
</script>

<style scoped>
.resume-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

.search-bar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.reject-btn {
  color: #F56C6C;
}

.reject-btn:hover {
  color: #f78989;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 20px;
}

:deep(.el-select) {
  width: 160px;
}

.resume-detail {
  padding: 10px;
}

.resume-header {
  display: flex;
  align-items: center;
}

.resume-name {
  font-size: 20px;
  font-weight: bold;
  margin-right: 15px;
}

.resume-gender {
  padding: 2px 10px;
  background-color: #ecf5ff;
  color: #409EFF;
  border-radius: 12px;
  font-size: 14px;
}

.detail-section {
  margin: 15px 0;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
  line-height: 24px;
}

.item-label {
  width: 120px;
  color: #606266;
  text-align: right;
  padding-right: 12px;
  font-weight: 500;
}

.item-value {
  flex: 1;
  color: #303133;
  word-break: break-all;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style> 